package hu.szyrt.bug;

import hu.szyrt.bug.db.DBHandler;
import hu.szyrt.bug.login.LoginHandler;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class SplashActivity extends Activity {

	private LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
	
	private ImageView splashImage;
	private Intent main, login;
	private Timer timer;
	
	private LoginHandler loginHandler;
	private DBHandler dbHandler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {	
		super.onCreate(savedInstanceState);
		
		this.loginHandler = new LoginHandler(this);
		this.dbHandler = new DBHandler(this);
		
		main = new Intent(this, MainActivity.class);
		main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);		
		login = new Intent(this, LoginActivity.class);
		login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		
		splashImage = new ImageView(this);		
		splashImage.setImageResource(R.drawable.splash);
		splashImage.setFocusable(false);
		splashImage.setFocusableInTouchMode(false);
		splashImage.setLayoutParams(params);
		splashImage.setScaleType(ScaleType.FIT_XY);
		splashImage.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startMain();
			}
		});
		
		setContentView(splashImage, params);
		
		if(!dbHandler.isInstalled())
			startDBInstall();
		else
			startTimer();
	}
	
	private void startDBInstall(){
		new Thread(new Runnable() {
			public void run() {
				try {
					dbHandler.install();
					Thread.sleep(500);
					runOnUiThread(new Runnable() {
						public void run() {
							startMain();
						}
					});					
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	private void stopTimer(){
		if(timer != null){
			timer.cancel();
			timer.purge();
		}
	}
	
	private void startTimer(){
		stopTimer();
		timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				startMain();
			}
		}, 1000);
	}
	
	
	private void startMain() {
		stopTimer();		
		startActivity(loginHandler.isLoggedIn() ? main : login);
		finish();	
	}

	
}
